<template>
  <div id="app">
    <div class="container">
      <div class="left-panel">
        <el-tree :data="directoryData" :props="defaultProps" @node-click="handleNodeClick">
          <template #default="{ node, data }">
            <div class="custom-tree-node">
              <span>{{ node.label }}</span>
              <el-button v-if="data.type === 'file'" type="text" size="mini" @click.stop="selectFile(data)">
                Select
              </el-button>
            </div>
          </template>
        </el-tree>
      </div>
      <div class="right-panel">
        <img v-if="selectedFile" :src="selectedFile.path" alt="Selected File" />
        <p v-else>No file selected</p>
      </div>
    </div>
  </div>
</template>

<script setup>
import { ref, onMounted } from 'vue';
import axios from 'axios';

const directoryData = ref([]);
const selectedFile = ref(null);

const defaultProps = {
  children: 'children',
  label: 'name',
};

const fetchDirectoryData = async () => {
  try {
    const response = await axios.get('/json/data.json');
    directoryData.value = response.data.children.map(item => ({
      ...item,
      type: item.children ? 'directory' : 'file'
    }));
  } catch (error) {
    console.error('Error fetching directory data:', error);
  }
};

const handleNodeClick = (data) => {
  if (data.type === 'file') {
    selectFile(data);
  }
};

const selectFile = (file) => {
  if (file.type === 'file' && file.name.match(/\.(jpg|jpeg|png|gif)$/i)) {
    selectedFile.value = file;
  } else {
    selectedFile.value = null;
  }
};

onMounted(() => {
  fetchDirectoryData();
});
</script>

<style>
#app {
  font-family: 'Microsoft YaHei', sans-serif;
  text-align: center;
  margin-top: 60px;
}

.container {
  display: flex;
  justify-content: space-between;
  max-width: 1200px;
  margin: 0 auto;
}

.left-panel {
  width: 30%;
  border-right: 1px solid #ccc;
  padding: 20px;
  overflow-y: auto;
  max-height: 600px;
}

.right-panel {
  width: 70%;
  padding: 20px;
}

.right-panel img {
  max-width: 100%;
  max-height: 600px;
  object-fit: contain;
}

.custom-tree-node {
  display: flex;
  align-items: center;
  justify-content: space-between;
  font-size: 14px;
  padding-right: 8px;
}
</style>
